package com.cuile.littletools.create


import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlur
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.graphics.drawable.toBitmap
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.NavHostFragment
import com.cuile.littletools.LittleToolsContacts.CREATE_RESULT_KEY
import com.cuile.littletools.LittleToolsContacts.REQUEST_ALBUM_BG
import com.cuile.littletools.LittleToolsContacts.REQUEST_ALBUM_LOGO
import com.cuile.littletools.R
import com.cuile.littletools.createQRCodeBitmap
import kotlinx.android.synthetic.main.fragment_qr_result.*
import petrov.kristiyan.colorpicker.ColorPicker
import java.io.File
import java.io.FileOutputStream



/**
 * A simple [Fragment] subclass.
 *
 */
class QrResultFragment : Fragment() {
    private val BIG = 600
    private val MID = 400
    private val SMALL = 200
    var qrImageSize = MID

    private var fgColor = Color.BLACK
    private var bgColor = Color.WHITE
    private var qrContent = ""
    private var logoImgUri: Uri? = null
    private var bgImgUri: Uri? = null


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {


        return inflater.inflate(R.layout.fragment_qr_result, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        qrContent = arguments?.getString(CREATE_RESULT_KEY)!!
        Log.i("QrResultFragment", qrContent)

        qrImgSizeRadioGroup.setOnCheckedChangeListener { _, id ->
            when(id) {
                R.id.qr_img_size_big -> {
                    qrImageSize = BIG
                }
                R.id.qr_img_size_mid -> {
                    qrImageSize = MID
                }
                R.id.qr_img_size_small -> {
                    qrImageSize = SMALL
                }
            }

            createAndSetImg()
        }
        qrImgSizeRadioGroup.check(R.id.qr_img_size_big)

        qrFgColorBtn.setOnClickListener {
            val fgClorPicker = ColorPicker(activity)
            fgClorPicker.setColors(arrayListOf("#e6194B", "#3cb44b", "#ffe119", "#4363d8", "#f58231", "#911eb4", "#42d4f4", "#f032e6", "#bfef45", "#fabebe", "#469990", "#e6beff", "#9A6324", "#fffac8", "#800000", "#aaffc3", "#808000", "#ffd8b1", "#000075", "#a9a9a9", "#ffffff", "#000000"))
            fgClorPicker.show()
            fgClorPicker.setOnChooseColorListener(object :ColorPicker.OnChooseColorListener{
                override fun onChooseColor(position: Int, color: Int) {
                    fgColor = color
                    qrFgColorTV.setBackgroundColor(fgColor)

                    createAndSetImg()
                }

                override fun onCancel() {}
            })
        }

        qrBgColorBtn.setOnClickListener {
            val bgClorPicker = ColorPicker(activity)
            bgClorPicker.setColors(arrayListOf("#e6194B", "#3cb44b", "#ffe119", "#4363d8", "#f58231", "#911eb4", "#42d4f4", "#f032e6", "#bfef45", "#fabebe", "#469990", "#e6beff", "#9A6324", "#fffac8", "#800000", "#aaffc3", "#808000", "#ffd8b1", "#000075", "#a9a9a9", "#ffffff", "#000000"))
            bgClorPicker.show()
            bgClorPicker.setOnChooseColorListener(object :ColorPicker.OnChooseColorListener{
                override fun onChooseColor(position: Int, color: Int) {
                    bgColor = color
                    qrBgColorTV.setBackgroundColor(bgColor)

                    createAndSetImg()
                }

                override fun onCancel() {}
            })
        }

        qrAddLogoBtn.setOnClickListener {
            getAlbumImg(REQUEST_ALBUM_LOGO)
        }

        qrChangeBgPic.setOnClickListener {
            getAlbumImg(REQUEST_ALBUM_BG)
        }

        qrResultBottomAppBar.setNavigationOnClickListener {
            NavHostFragment.findNavController(this).navigateUp()
        }

        qrResultFloatingActionBtn.setOnClickListener {
            val qrBitmap = qrResultIV.drawable.toBitmap()

            val storePath = Environment.getExternalStorageDirectory().absolutePath + File.separator + "qrimg"
            val appDir = File(storePath)
            if (!appDir.exists()) {
                appDir.mkdir()
            }
            val fileName = System.currentTimeMillis().toString() + ".jpg"

            val imgFile = File(appDir, fileName)
            val fos = FileOutputStream(imgFile)
            qrBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos)
            fos.flush()
            fos.close()

            val uri = Uri.fromFile(imgFile)
            context?.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
            Toast.makeText(context, "二维码图片已存入本地", Toast.LENGTH_SHORT).show()
        }
    }

    private fun getAlbumImg(requestCode: Int) {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
                .addCategory(Intent.CATEGORY_OPENABLE)
                .setType("image/*")

        startActivityForResult(intent, requestCode)
    }

    private fun createAndSetImg() {
        val qrBitmap = qrContent.createQRCodeBitmap(
                qrImageSize,
                "UTF-8",
                "H",
                "2",
                fgColor,
                bgColor,
                getBitmapByUri(bgImgUri),
                getBitmapByUri(logoImgUri),
                0.2F)
        qrResultIV.setImageBitmap(qrBitmap)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ALBUM_LOGO) {
            logoImgUri = data?.data
            createAndSetImg()
        } else if (requestCode == REQUEST_ALBUM_BG) {
            bgImgUri = data?.data
            createAndSetImg()
        }
    }

    private fun getBitmapByUri(uri: Uri?, isBlur: Boolean = true): Bitmap? =
            if (uri == null) {
                null
            } else {
                val srcBitmap = MediaStore.Images.Media.getBitmap(activity?.contentResolver, uri)
                if (isBlur) {
                    blurBitmap(srcBitmap, 25.0F)
                } else {
                    srcBitmap
                }
            }
    private fun blurBitmap(bitmap: Bitmap, blurStage: Float): Bitmap {
        val outBitmap = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)

        val rs = RenderScript.create(context)
        val blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs))

        val allIn = Allocation.createFromBitmap(rs, bitmap)
        val allOut = Allocation.createFromBitmap(rs, outBitmap)

        // 0..25
        blurScript.setRadius(blurStage)

        blurScript.setInput(allIn)
        blurScript.forEach(allOut)

        allOut.copyTo(outBitmap)

        bitmap.recycle()
        rs.destroy()

        return outBitmap
    }
}
